<template>
  <form-model
    ref="createModal"
    :formTitle="formTitle"
    :width="608"
    :form="form"
    :rules="rules"
    @ok="handleOk"
  >
    <span style="position: absolute;left: 110px;top: -32px;">
      {{ $t('targetVersion') }}: {{ recordData.name }}
    </span>
    <!-- 文件类型 -->
    <a-form-model-item
      :label="$t('fileType')"
      v-if="newFileType==='1'&&!form.id"
      :prop="newFileType==='1'&&!form.id?'resourceType':''"
    >
      <a-select
        v-model="form.resourceType"
        showSearch
        allow-clear
        optionFilterProp="children"
        :filterOption="$commonFun.filterOption"
        :disabled="resourceTypeReadOnly"
        @change="changeResourceType"
      >
        <a-select-option
          v-for="(item,index) in typeList"
          :key="index"
          :value="item.value"
          :title="$t(item.key)"
        >{{ $t(item.key) }}</a-select-option>
      </a-select>
    </a-form-model-item>
    <!-- 摘要算法 -->
    <a-form-model-item
      :label="$t('zysf')"
      prop="hashAlgorithm"
      v-if="newFileType==='1'&&!form.id"
    >
      <a-select
        v-model="form.hashAlgorithm"
        showSearch
        allow-clear
        :placeholder="$t('pleaseSelect')"
        optionFilterProp="children"
        :filterOption="$commonFun.filterOption"
        style="width: 100%"
        @change="changeHashAlgorithm"
      >
        <a-select-option
          v-for="(key,val,index) in digestAlgorithm"
          :key="index"
          :value="parseInt(val,10)"
        >
          {{ key }}
        </a-select-option>
      </a-select>
    </a-form-model-item>
    <!-- 是否手动输入摘要值 -->
    <a-checkbox
      v-if="newFileType==='1'&&!form.id"
      style="position:absolute;right:0"
      :checked="isManualEntry"
      @change="isManualEntry=$event.target.checked">
      {{ $t('manualInput') }}
    </a-checkbox>
    <!-- 摘要值 -->
    <a-form-model-item
      :label="$t('zyz')"
      v-if="newFileType==='1'&&!form.id"
    >
      <!-- 手动输入 -->
      <a-textarea
        v-if="isManualEntry"
        style="width: 100%"
        v-model="form.checksum"
        :placeholder="$t('pleaseInput')"
        :rows="4"
      ></a-textarea>
      <!-- 自动填充 md5或者sha256-->
      <a-textarea
        v-else
        style="width: 100%"
        disabled
        :rows="4"
        v-model="fileInfor.fileObject[digestAlgorithm[form.hashAlgorithm]]"
      ></a-textarea>
    </a-form-model-item>
    <!-- 上传文件 -->
    <a-form-model-item
      v-if="newFileType==='1'&&!form.id"
    >
      <template slot="label">
        <span class="requiredSty">
          {{ $t('uploadFile') }}
        </span>
      </template>
      <a-input
        ref="userNameInput"
        readOnly
        :value="fileInfor.fileObject.fileName"
        :placeholder="$t('pleaseUpload')"
      >
        <a-icon
          @click="upload"
          slot="suffix"
          type="upload"
        />
      </a-input>
      <chunk-upload
        ref="uploadPlug"
        :showDom="false"
        fileStoreField="fileObject"
        :recordData="fileInfor"
        uploadType="1"
        :size="20*1024*1024*1024"
        :hashAlgorithm="form.hashAlgorithm"
      >
      </chunk-upload>
    </a-form-model-item>
    <!-- 原始版本 差分包或者在线差分才展示-->
    <a-form-model-item
      v-if="!form.id&&form.resourceType!=='10'"
      prop="sourceVersionId"
    >
      <template v-slot:label>
        <span>{{ $t('originalVersion') }}</span>
        <question-mark-tip
          :tip-title="newFileType==='2'? $t('zxzzsourceTip'):$t('scwjsourceTip')"
          :popupContainer="$commonFun.getPopupContainer"
        ></question-mark-tip>
      </template>
      <VersionSelect v-model="form.sourceVersionId" :clear="true" :append-to-body="false"
                     :ecuModuleId="recordData.ecuModuleId"
                     :targetVersionId="recordData.id"
      />
<!--      <a-select-->
<!--        v-model="form.sourceVersionId"-->
<!--        showSearch-->
<!--        allow-clear-->
<!--        :placeholder="$t('pleaseSelect')+$t('originalVersion').toLowerCase()"-->
<!--        optionFilterProp="children"-->
<!--        :filterOption="$commonFun.filterOption"-->
<!--        style="width: 100%"-->
<!--        :disabled="form.resourceType==='10'"-->
<!--        :mode="newFileType==='2'?'multiple':'default'"-->
<!--      >-->
<!--        <a-select-option-->
<!--          v-for="(item,index) in soutarpacklist"-->
<!--          :key="index"-->
<!--          :value="item.id"-->
<!--          :title="item.name"-->
<!--        >{{ item.name }} 【{{$store.getters.getDictCodeObj('versionTypeDictCode')[item.versionType] || item.versionType}}】</a-select-option>-->
<!--      </a-select>-->
    </a-form-model-item>
    <!-- 差分素材文件 -->
    <a-form-model-item prop="materialFileType" v-if="newFileType==='2'&&!form.id">
      <template v-slot:label>
        <span>{{ $t('diffMaterialFile') }}</span>
        <question-mark-tip
          :tip-title="$t('clbtip')"
          :popupContainer="$commonFun.getPopupContainer"
        ></question-mark-tip>
      </template>
      <a-select
        v-model="form.materialFileType"
        showSearch
        allow-clear
        :placeholder="$t('pleaseSelect')+$t('diffMaterialFile').toLowerCase()"
        optionFilterProp="children"
        :filterOption="$commonFun.filterOption"
        style="width: 100%"
      >
        <a-select-option :value="1">{{ $t('versionFile') }}</a-select-option>
        <a-select-option :value="2">{{ $t('wholePackage') }}</a-select-option>
      </a-select>
    </a-form-model-item>
    <!-- 预计安装时间 -->
    <a-form-model-item :label="$t('estimatedInstallTime')+'(s)' " prop="installTime">
      <a-input-number
        style="width: 100%"
        v-model="form.installTime"
        :placeholder="$t('pleaseInput')+$t('estimatedInstallTime').toLowerCase()"
      ></a-input-number>
    </a-form-model-item>
    <!-- 超时时长 -->
    <a-form-model-item :label="$t('timeout')+'(s)'" prop="overTime">
      <a-input-number
        style="width: 100%"
        v-model="form.overTime"
        :placeholder="$t('pleaseInput')+$t('timeout').toLowerCase()"
      ></a-input-number>
    </a-form-model-item>
    <!-- dll文件类 -->
    <a-form-model-item v-if="!dllName" :label="$t('dllFileClassName')" prop="dllName">
      <a-select
        v-model="form.dllName"
        showSearch
        allow-clear
        :placeholder="$t('pleaseSelect')+$t('dllFileClassName')"
        optionFilterProp="children"
        :filterOption="$commonFun.filterOption"
        style="width: 100%"
      >
        <a-select-option
          v-for="(item,index) in dllClassNameDictCode"
          :key="index"
          :value="item.value"
          :title="item.name"
        >{{ item.name }}</a-select-option>
      </a-select>
    </a-form-model-item>
  </form-model>

</template>
<script>
import FormModel from '@/components/SelfModal/FormModel'
import ChunkUpload from '@/components/Upload/ChunkUpload'
import { typeList } from './config'
import { mapState } from 'vuex'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import { checkIsRangeInteger } from '@/utils/validate'
import VersionSelect from '@/views/components/VersionSelect'
export default {
  name: 'UploadUpgradePackage',
  components: { FormModel, ChunkUpload, QuestionMarkTip,VersionSelect },
  props: {
    dllName: {
      type: String,
      default: ''
    },
    //   当前版本信息
    recordData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 上传文件1 在线制作2
    newFileType: {
      type: String,
      default: '1'
    }
  },
  computed: {
    ...mapState({
      // 摘要算法
      digestAlgorithm: (state) => state.dict.digestAlgorithm,
      dllNameDictCode: (state) => state.dict.dllNameDictCode,
      dllClassNameDictCode: (state) => state.dict.dllClassNameDictCode,
    })
  },
  data () {
    return {
      resourceTypeReadOnly: false,
      form: {},
      rules: {
        resourceType: [{ required: true, trigger: 'change', message: this.$t('pleaseSelect') }],
        materialFileType: [{ required: true, message: this.$t('pleaseInput') }],
        sourceVersionId: [{ required: true, trigger: 'change', message: this.$t('pleaseSelect') }],
        hashAlgorithm: [{ required: true, message: this.$t('pleaseInput') }],
        // lxhmodifyxccode
        installTime: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkIsRangeInteger(1, 2147483647) }
        ],
        // lxhmodifyxccode
        overTime: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkIsRangeInteger(1, 2147483647) }
        ],
        dllName: [{ required: true, message: this.$t('pleaseSelect') }]
      },
      formTitle: '',
      fileInfor: { fileObject: { uploadLoadding: false } },
      typeList,
      isManualEntry: false // 是否手动输入
    }
  },
  methods: {
    // 改变包类型时需要初始化原始版本
    changeResourceType (value) {
      if (value === '10') {
        this.form.sourceVersionId = undefined
      }
    },
    changeHashAlgorithm () {
      // 切换算法后 重新上传文件
      this.fileInfor = { fileObject: { uploadLoadding: false } }
      this.$refs.uploadPlug.resetUpload()
    },
    validMaterialFileId () {
      return new Promise((resolve) => {
        const vm = this
        let materialFileId = ''
        vm.$api.validMaterialFileId({ id: vm.recordData.id }).then(res => {
          materialFileId = res.data
          resolve(materialFileId)
        })
      })
    },
    async handleAdd (initData) {
      // 关闭是否支持差分校验
      // const materialFileId = await this.validMaterialFileId()
      // 上传文件
      if (this.newFileType === '1') {
        this.formTitle = this.$t('uploadFile')
      if (initData && initData.resourceType) {
        this.resourceTypeReadOnly = true;
      }
        initData= Object.assign( {
          sourceVersionId: undefined,
          installTime: '',
          overTime: '',
          resourceType : '20',
          hashAlgorithm : 1
          // dllName: ''
        }, initData);
      this.form = { ...initData }
      this.fileInfor = { fileObject: { uploadLoadding: false } }
      this.$refs.createModal.add()
    }
    },
    handleEdit (record) {
      this.formTitle = this.$t('editFile')
      this.form = { ...record }
      this.$refs.createModal.add()
    },
    handleOk () {
      const vm = this
      const values = { ...vm.form }
      let apiFun = ''
      if (values.id) {
        //   编辑保存
        apiFun = 'editSave'
      } else if (!values.id && vm.newFileType === '1') {
        //   上传文件保存
        apiFun = 'saveFileResource'
      } else {
        // 在线制作方式保存
        apiFun = 'saveDiffResource'
      }
      vm[apiFun](values).then(() => {
        vm.$refs.createModal.visible = false
        vm.$emit('refreshData')
      }).finally(() => {
        vm.$refs.createModal.confirmLoading = false
      })
    },
    // 编辑保存
    editSave (values) {
      const vm = this
      return new Promise((resolve) => {
        vm.$api.editResource({
          id: values.id,
          installTime: values.installTime,
          overTime: values.overTime,
          dllName: values.dllName
        }).then(() => {
          resolve()
        })
      })
    },
    // 上传文件保存
    saveFileResource (values) {
      const vm = this
      return new Promise((resolve) => {
        //   上传文件时必须要有文件
        if (!values.id && vm.newFileType === '1' && !vm.fileInfor.fileObject.fileId) {
          vm.$message.warning(vm.$t('hasUploaded'))
          return
        }
        // eslint-disable-next-line no-param-reassign
        values.fileId = vm.fileInfor.fileObject.fileId
        // eslint-disable-next-line no-param-reassign
        values.fileName = vm.fileInfor.fileObject.fileName
        // eslint-disable-next-line no-param-reassign
        values.targetVersionId = vm.recordData.id
        // eslint-disable-next-line no-restricted-syntax
        for (const key in values) {
          if (values[key] === '') {
            // eslint-disable-next-line no-param-reassign
            values[key] = undefined
          }
        }
        // 如果是自动填充需要用生成的摘要值
        if (!vm.isManualEntry) {
          // eslint-disable-next-line no-param-reassign
          values.checksum = vm.fileInfor.fileObject[vm.digestAlgorithm[vm.form.hashAlgorithm]]
        }
        // 校验摘要值
        if (values.checksum !== vm.fileInfor.fileObject[vm.digestAlgorithm[vm.form.hashAlgorithm]]) {
          vm.$message.warning(vm.$t('summaryIn'))
          return
        }
        // eslint-disable-next-line no-param-reassign
        values.dllName = this.dllName?this.dllName:this.form.dllName
        values.versionType = 1 // 配置文件2 零件版本的升级包1
        console.log(values)
        const { ...paramResource } = values
        vm.$api.addResource(paramResource).then(() => {
          // 刷新软件版本列表
          vm.$emit('refreshSoftVersion')
          vm.fileInfor = { fileObject: { uploadLoadding: false } }
          vm.$refs.uploadPlug.resetUpload()
          resolve()
        })
      })
    },
    // 在线制作方式保存
    saveDiffResource (values) {
      const vm = this
      return new Promise((resolve) => {
        vm.$api.diffResourceSave({
          targetVersionId: vm.recordData.id,
          sourceVersionIds: values.sourceVersionId,
          materialFileType: values.materialFileType,
          installTime: values.installTime,
          dllName: values.dllName,
          overTime: values.overTime,
          encryptType: vm.recordData.ecu ? vm.recordData.ecu.encryptType : '' // 零件的加密方式
        }).then(() => {
          resolve()
        })
      })
    },
    upload () {
      this.$refs.uploadPlug.upload()
    }
  }
}
</script>
